import sys 
sys.path.append("core_q3_fm")
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from plotly.offline import download_plotlyjs, init_notebook_mode,  plot
from Surface_Plot  import surface_parameters_orig
import plotly.graph_objects as go 
import numpy as np


#X=np.loadtxt('Estimated_parameters.txt') 

X = np.loadtxt("./core_q3_fm/data_q3_fm.txt")
#Scale the points
scaler = MinMaxScaler()
#scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
inertia = []

#Determine the optimal number of clusters
for i in range(1,11):
    kmeans = KMeans(n_clusters=i, init="k-means++",n_init=10,tol=1e-04)
    kmeans.fit(X)
    inertia.append(kmeans.inertia_)
# fig = go.Figure(data=go.Scatter(x=np.arange(1,11),y=inertia))

# fig.update_layout(title="Inertia vs Cluster Number",xaxis=dict(range=[0,11],title="Cluster Number"),
#                   yaxis={'title':'Inertia'}, annotations=[
#         dict(
#             x=3,
#             y=inertia[2],
#             xref="x",
#             yref="y",
#             text="Elbow! (Optimal number of cluseters)",
#             showarrow=True,
#             arrowhead=7,
#             ax=20,
#             ay=-40
#         )])

# fig.write_image('Elbow.pdf')
# plot(fig)



#Perform the clustering
kmeans = KMeans(
        n_clusters=3, init="k-means++",
        n_init=10,
        tol=1e-04, random_state=10)

kmeans.fit(X)
#Obtain the centers of the clusters
parameters_LSTM_scaled = kmeans.cluster_centers_
parameters_LSTM_unscaled = parameters_LSTM_scaled*(scaler.data_max_ - scaler.data_min_) + scaler.data_min_

X_clustered = np.zeros((X.shape[0], 7))
X_clustered[:,0:6] = X
X_clustered[:,6] = kmeans.labels_
#Plot the clusters
shape_1 = 45
shape_2 = 13
clusters_reshaped = np.reshape(kmeans.labels_, (shape_1, shape_2))
Tr=surface_parameters_orig(clusters_reshaped,'tr',' ',' ')